package edu.maine.usm.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.cell.client.DatePickerCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.Range;

import edu.maine.usm.dto.EnrollmentDTO;
import edu.maine.usm.rpc.EnrollmentServiceAsync;

public class EnrollmentListView extends Composite {

	private static EnrollmentListViewUiBinder uiBinder = GWT
			.create(EnrollmentListViewUiBinder.class);
	
	@UiField CellTable<EnrollmentDTO> enrollmentTable;
	@UiField Button refreshListBtn;

	private ListDataProvider<EnrollmentDTO> provider;

	private EnrollmentServiceAsync service;

	interface EnrollmentListViewUiBinder extends
			UiBinder<Widget, EnrollmentListView> {
	}

	public EnrollmentListView(EnrollmentServiceAsync service) {
		this.service = service; 
		
		initWidget(uiBinder.createAndBindUi(this));
		TextColumn<EnrollmentDTO> textCol = new TextColumn<EnrollmentDTO>() {
			@Override
			public String getValue(EnrollmentDTO object) {
				return object.getExternalId();
			}
		};
		
		Column<EnrollmentDTO, Date> enrollmentDate = new Column<EnrollmentDTO, Date>(new DatePickerCell()) {
			@Override
			public Date getValue(EnrollmentDTO object) {
				return object.getReferenceDate();
			}
		};
		enrollmentDate.setFieldUpdater(new FieldUpdater<EnrollmentDTO, Date>() {
			public void update(int index, EnrollmentDTO object, Date value) {
				
			}
		});
		
		
		enrollmentTable.addColumn(textCol, "External Identifier");
		enrollmentTable.addColumn(enrollmentDate, "Enrollment Date");
		provider = new ListDataProvider<EnrollmentDTO>();
		provider.addDataDisplay(enrollmentTable);
	}
	
	@UiHandler("refreshListBtn")
	public void handleListClick(ClickEvent event) {
		service.getPersistedEnrollments(new AsyncCallback<ArrayList<EnrollmentDTO>>() {
			public void onFailure(Throwable caught) {
				Window.alert("Error retrieving the list of enrollments.");
			}

			public void onSuccess(ArrayList<EnrollmentDTO> result) {
				enrollmentTable.setVisibleRangeAndClearData(new Range(0, result.size()), true);
				
				List<EnrollmentDTO> enrollments = provider.getList();
				enrollments.clear();
				for(EnrollmentDTO dto : result) {
					enrollments.add(dto);
				}
				
				
			}
		});
	}


}
